import React, { useEffect, useRef, useState } from 'react'
import { Link, useHistory } from 'react-router-dom'

export default function NotFound() {
	const [time, setTime] = useState(3)
	const history = useHistory()
    const timeRef = useRef(-1)

	useEffect(() => {
		const intervalId = setInterval(() => {
			/* setTime((time) => {
				if (time === 1) {
					clearInterval(intervalId)
					// 路由跳转后在跟新useState， 将会报错
					history.push('/home')
				}
				return time - 1
			}) */

            setTime(time => {
                timeRef.current = time - 1
                return time - 1
            })

            if(timeRef.current === 0) {
                clearInterval(intervalId)
                history.push('/home')
            }
		}, 1000)
	}, [history])
	return (
		<div>
			<h1>对不起, 你访问的内容不存在....</h1>
			<p>
				{time}s后. 返回<Link to="/home">首页</Link>
			</p>
		</div>
	)
}
